import requests,json

# 获取access_token 详见：https://work.weixin.qq.com/api/doc/90000/90135/91039
# corpid 企业ID  获取方式参考：https://work.weixin.qq.com/api/doc/90000/90135/90665#corpid
# corpsecret 应用的凭证密钥  获取方式参考：https://work.weixin.qq.com/api/doc/90000/90135/90665#secret
def getAccessToken(corpid,secret):
    url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=' + corpid + '&corpsecret=' + secret
    req = requests.get(url)
    try:
        msg = json.loads(req.text)
    except:
        print('access_token请求出错')
    print(msg)
    return msg['access_token']

'''
推送消息
agentId 应用ID
title 消息标题
media_id 图文消息缩略图的media_id key
author 图文消息的作者
content 消息内容
digest 图文消息的描述
url 阅读原文跳转的链接
'''
def sendMsg(access_token,agentId,title,media_id,author,url,content,digest):
    sendUrl = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' + access_token
    data = {
    "touser" : "@all", #成员ID列表（消息接收者，最多支持1000个）
    #"toparty" : ["partyid1","partyid2","LinkedId1/partyid1","LinkedId2/partyid2"], # 部门ID列表，最多支持100个。
    #"totag" : ["tagid1","tagid2"], #本企业的标签ID列表
    "toall" : 0, #1表示发送给应用可见范围内的所有人（包括互联企业的成员），默认为0
    "msgtype" : "mpnews", # 消息类型，此时固定为：news 图文消息
    "agentid" : agentId, #企业应用的id，整型。可在应用的设置页面查看
    "mpnews" : {
       "articles" : [
            {
               "title" : title,
               "thumb_media_id": media_id,
               "author": author,
               "content_source_url": '',
               "content": content + '</br></br>本消息来自' + '<a href="https://gitee.com/lxfap">'+ author +' https://gitee.com/lxfap</a>',
               "digest": digest
           }
        ]
    }
    }
    sendreq = requests.post(sendUrl,json.dumps(data))
    if json.loads(sendreq.text)['errcode'] == 0:
        print('推送成功')



